<template>
  <div class="filter-value">
    <selectWithoutHttp v-model="filterItem[keyName]" :list-data="fieldListData" filterable class="select-field mr10 width-120" label-name="name" key-name="key" placeholder="请选择字段" @change="changeKeyword" />
    <selectWithoutHttp v-if="isShowMath" v-model="filterItem.math" :list-data="mathOptions" class="select-math mr10 width-80" label-name="label" key-name="value" placeholder="请选择运算符" @change="changeValue" />
    <selectWithoutHttp v-if="hasValueType" v-model="filterItem.valueType" :list-data="valueTypes" class="select-math mr10 width-80" label-name="label" key-name="value" placeholder="请选择类型" @change="changeValueType" />
    <selectWithoutHttp v-if="hasValueType && valueTypeFlag && filterItem.valueType === 1" v-model="computedValue" :list-data="fieldList" filterable class="width-240" label-name="name" key-name="key" placeholder="请选择字段" />
    <template v-else-if="valueTypeFlag">
      <!-- 用户类型 -->
      <selectWithoutHttp v-if="filedType === 'user' && isShowUserType" v-model="filterItem.userType" :list-data="userTypeList" class="width-120" style="margin-right: 10px;" placeholder="请选择条件类型" @change="changeUserType" />
      <!-- 数值 -->
      <el-input
        v-if="filedType === 'number'"
        v-model="computedValue"
        oninput="if(value>999999999999)value=999999999999;if(value<-999999999999)value=-999999999999"
        size="small"
        placeholder="请输入数值"
        type="number"
        class="width-240" />
      <!-- 下拉、职位、开关 -->
      <selectWithoutHttp
        v-else-if="multipleSelectTypes.includes(filedType) || tableTypes.includes(filedType) || filedType === 'post' || filedType === 'switch' || filedType==='status'"
        v-model="computedValue"
        :list-data="handelList(filedType)"
        :multiple="multipleSelectTypes.includes(filedType) || filedType === 'post'"
        :label-name="filedType === 'post'?'name':'id'"
        :filter-method="filterMethod"
        class="width-240"
        key-name="id"
        clearable
        filterable
        placeholder="请选择" />
      <!-- 时间 -->
      <el-date-picker
        v-else-if="filedType === 'date'"
        v-model="computedValue"
        :type="getType(filedElement)"
        :editable="false"
        :clearable="true"
        :format="filedElement.options.format"
        size="small"
        value-format="timestamp"
        placeholder="请选择时间"
        class="width-240"
      />
      <!-- 地址 -->
      <ThreeLevelArea
        v-else-if="filedType === 'address'"
        :select-type="filedElement?filedElement.options.addressType || 'region':'region'"
        :selected-options="computedValue"
        placeholder="请输入地址"
        clearable
        separator="-"
        cascader-size="small"
        @update:options="threeLevelArea($event)" />
      <!-- 可选择子部门 -->
      <DeptSelect
        v-else-if="filedType === 'department' || (filedType === 'user' && filterItem.userType === 2 && isShowUserType)"
        v-model="computedValue"
        :is-can-include-sub-dept="isCanIncludeSubDept"
        :is-include-sub-dept="isIncludeSubDept"
        :element="handelElement()"
        class="width-240"
        @isSubDeptChange="isSubDeptChange" />
      <!-- 用户 -->
      <SelectUser v-else-if="(!isShowUserType && filedType === 'user') || (isShowUserType && filedType === 'user' && filterItem.userType === 0)" v-model="computedValue" :default-value="computedValue" class="width-240" multiple />
      <!-- 3:角色组 或 4:BP类型-->
      <selectWithoutHttp
        v-else-if="isShowUserType && filedType === 'user' && (filterItem.userType === 3 || filterItem.userType === 4)"
        v-model="computedValue"
        :list-data="filterItem.userType === 3?roleGroupList:BPList"
        :placeholder="`请选择${filterItem.userType === 3?'角色组':'BP类型'}`"
        :item-max-width="240"
        :key-name="filterItem.userType === 3?'id':'name'"
        filterable
        class="width-240"
        label-name="name"
        multiple
        clearable />
      <el-input v-else-if="!isShowUserType || filedType !== 'user'" :maxlength="500" v-model="computedValue" type="text" class="width-240" placeholder="请输入" size="small" />
    </template>
  </div>
</template>

<script>
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import DeptSelect from '@/views/legal/process/components/formMake/components/deptSelect.vue';
import SelectUser from '@/components/Common/baseComponent/selectUser/index';
import ThreeLevelArea from '@/components/ThreeLevelArea';
import { getAllPost } from '@/api/user';
import { isNumberType } from '@/utils/formMakeUtils.js';
import { mapState } from 'vuex';
// import { format } from '@/filters/date';
export default {
  name: 'FilterValue',
  components: { selectWithoutHttp, SelectUser, ThreeLevelArea, DeptSelect },
  props: {
    parentValueKey: {
      type: String,
      default: ''
    },
    fieldList: { // 条件字段
      type: Array,
      default: () => ([])
    },
    filterItem: { // 当前筛选的item
      type: Object,
      default: () => ({})
    },
    keyName: { // 字段在filterItem中的 keyName
      type: String,
      default: 'keyword'
    },
    hasValueType: {
      type: Boolean,
      default: false
    },
    valueKeyName: { // 值的 keyName
      type: String,
      default: ''
    },
    isShowStatus: { // 是否增加状态
      type: Boolean,
      default: false
    },
    isCanIncludeSubDept: {
      type: Boolean,
      default: false
    },
    isIncludeSubDept: {
      type: Boolean,
      default: false
    },
    isShowUserType: { // 是否开启选择用户字段的条件类型，目前只有流程设计有开启
      type: Boolean,
      default: false
    },
    isShowMath: {
      type: Boolean,
      default: true
    },
    isShowAllLinkField: { // 是否包含关联表单的所有字段
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      multipleSelectTypes: ['select', 'radio', 'checkbox'],
      tableTypes: ['upAttachment', 'subform', 'linkForm', 'associatedApproval'],
      postList: [],
      statusList: [{ id: '待提交' }, { id: '审批中' }, { id: '已完成' }, { id: '已作废' }],
      valueTypeFlag: true,
      // 0: 自定义人员 1: 任务创建人 2: 选择部门 3: 角色组 4: 获取BP人员
      userTypeList: [
        { value: '自定义人员', id: 0 }, { value: '任务创建人', id: 1 }, { value: '选择部门', id: 2 },
        { value: '角色组', id: 3 }, { value: '获取BP人员', id: 4 }
      ]
    };
  },
  computed: {
    ...mapState({
      'BPList': state => state.formMake.BPList, // BP 类型
      'roleGroupList': state => state.formMake.roleGroups // 角色组
    }),
    computedValue: {
      get() {
        if (this.valueKeyName) {
          return this.filterItem[this.valueKeyName];
        }
        if (this.parentValueKey) {
          return this.filterItem[this.parentValueKey].value;
        }
        return this.filterItem.value;
      },
      set(val) {
        if (this.valueKeyName) {
          this.$set(this.filterItem, this.valueKeyName, val);
        } else if (this.parentValueKey) {
          this.$set(this.filterItem[this.parentValueKey], 'value', val);
        } else {
          this.$set(this.filterItem, 'value', val);
        }
        this.$emit('change', val);
      }
    },
    valueTypes() {
      if (['subform', 'linkForm', 'associatedApproval', 'upAttachment', 'status'].includes(this.filedType)) {
        return [{ value: 0, label: '值' }];
      }
      return [{ value: 0, label: '值' }, { value: 1, label: '字段' }];
    },
    filedType() { // 返回字段 type
      if (this.filterItem[this.keyName] === 'status') return 'status';
      if (!this.filterItem[this.keyName]) return '';
      const el = this.filedElement;
      if (el) {
        if ((!this.isShowAllLinkField && el.isLinkField) || isNumberType(el)) {
          return 'number';
        }
        return el ? el.type : '';
      }
      return '';
    },
    filedElement() {
      const formSubform = this.fieldList;
      if (formSubform) {
        const el = formSubform.find(i => i.key === this.filterItem[this.keyName]);
        return el || null;
      }
      return null;
    },
    selectOptions() {
      if (this.filedElement && this.filedElement.options && this.filedElement.options.options) {
        return this.filedElement.options.options;
      }
      return [];
    },
    mathOptions() {
      if (['number', 'date'].includes(this.filedType)) {
        return [
          { value: '=', label: '=' }, { value: '!=', label: '!=' },
          { value: '>', label: '>' }, { value: '<', label: '<' },
          { value: '>=', label: '>=' }, { value: '<=', label: '<=' }
        ];
      } else if (['formulaInput'].includes(this.filedType)) {
        return [
          { value: '=', label: '=' }, { value: '!=', label: '!=' },
          { value: '>', label: '>' }, { value: '<', label: '<' },
          { value: '>=', label: '>=' }, { value: '<=', label: '<=' },
          { value: '包含', label: '包含' }, { value: '不包含', label: '不包含' }
        ];
      } else if (['formulaInput', 'user', 'department', 'post', 'input', 'textarea', 'select', 'radio', 'checkbox'].includes(this.filedType)) {
        return [
          { value: '=', label: '=' }, { value: '!=', label: '!=' },
          { value: '包含', label: '包含' }, { value: '不包含', label: '不包含' }
        ];
      } else if (['switch', 'address', 'status'].includes(this.filedType)) {
        return [
          { value: '=', label: '=' }, { value: '!=', label: '!=' }
        ];
      } else if (this.tableTypes.includes(this.filedType)) {
        return [
          { value: '=', label: '=' }
        ];
      } else if (['richEditor'].includes(this.filedType)) {
        return [{ value: '包含', label: '包含' }, { value: '不包含', label: '不包含' }];
      }
      return [
        { value: '=', label: '=' }, { value: '!=', label: '!=' },
        { value: '>', label: '>' }, { value: '<', label: '<' },
        { value: '>=', label: '>=' }, { value: '<=', label: '<=' },
        { value: '包含', label: '包含' }, { value: '不包含', label: '不包含' }
      ];
    },
    fieldListData() {
      const statusItem = { name: '状态', key: 'status' };// 组件显隐添加增加状态字段
      const fieldListData = JSON.parse(JSON.stringify(this.fieldList));
      if (this.isShowStatus) { fieldListData.unshift(statusItem); }
      return fieldListData;
    }
  },
  created() {
    if (this.filedType === 'post') {
      this.queryAllPost();
    }
  },
  methods: {
    changeValue() {
      this.$emit('change', this.computedValue);
    },
    isSubDeptChange(e) {
      this.$emit('isSubDeptChange', e);
    },
    changeKeyword(val) {
      if (['richEditor'].includes(this.filedType)) {
        this.$set(this.filterItem, 'math', '包含');
      } else {
        this.$set(this.filterItem, 'math', '=');
      }
      this.$set(this.filterItem, 'userType', 0);
      if (this.hasValueType) this.$set(this.filterItem, 'valueType', 0);
      this.computedValue = '';
      const arrValue = ['user', 'department', 'post', 'address'];
      if (arrValue.includes(this.filedType) || this.multipleSelectTypes.includes(this.filedType)) {
        this.computedValue = [];
      }
      if (this.filedType === 'post') {
        this.queryAllPost();
      }
      this.$emit('changeKeyword', val, this.filterItem, this.filedType);
      this.valueTypeFlag = false;
      this.$nextTick(() => {
        this.valueTypeFlag = true;
      });
    },
    filterMethod(name) {
      if (this.filedType === 'post') {
        this.queryAllPost(name);
      }
    },
    queryAllPost(name = '') {
      const that = this;
      const params = {
        page: 1,
        perPage: 20,
        name
      };
      const postDataCache = that.$store.getters.postList;
      if (!params.name && postDataCache && postDataCache.data.items) {
        this.postList = postDataCache.data.items;
        return;
      }
      getAllPost(params).then(res => {
        if (res.data && res.data.items) {
          res.data.items = res.data.items.map(name => ({ id: name, name }));
          if (params.page === 1 && !params.name) that.$store.commit('SET_POSTLIST', res);
          this.postList = res.data.items;
        }
      });
    },
    handelList(type) {
      if (type === 'switch') {
        return [{ id: '是' }, { id: '否' }];
      } else if (this.tableTypes.includes(type)) {
        return [{ id: '数据为空' }, { id: '数据不为空' }];
      }
      if (type === 'status') return this.statusList;
      return type === 'post' ? this.postList : this.selectOptions;
    },
    threeLevelArea(data) {
      // if (Array.isArray(data)) {
      //   this.computedValue = data.join('-');
      // } else {
      // }
      this.computedValue = data;
      this.changeValue();
    },
    changeValueType(e) {
      if (e === 1) {
        // 字段
        this.computedValue = '';
      } else {
        // 值
        this.computedValue = '';
        const arrValue = ['user', 'department', 'post', 'address'];
        if (arrValue.includes(this.filedType) || this.multipleSelectTypes.includes(this.filedType)) {
          this.computedValue = [];
        }
        this.changeValue();
      }
      this.valueTypeFlag = false;
      this.$nextTick(() => {
        this.valueTypeFlag = true;
      });
    },
    changeUserType() {
      this.computedValue = '';
    },
    handelElement() {
      const el = {
        type: 'department',
        options: {
          selectChild: true,
          multiple: true,
          placeholder: '请选择部门'
        }
      };
      return el;
    },
    getType(element) {
      const format = element.options.format;
      const isRange = element.options.isRange;
      if (format === 'yyyy/MM') {
        return `month${isRange ? 'range' : ''}`;
      } else if (format === 'yyyy/MM/dd HH:mm:ss') {
        return `datetime${isRange ? 'range' : ''}`;
      }
      return `date${isRange ? 'range' : ''}`;
    }
    // changeTime(e, formatStr) {
    //   const date = format(e, this.getFormat(formatStr));
    //   const computedValue = new Date(date).valueOf();
    //   console.log(this.computedValue, computedValue, date, formatStr);
    // },
    // getFormat(format) {
    //   if (!format) return 'YYYY/MM/DD HH:mm:ss';
    //   format = format.replace('yyyy', 'YYYY');
    //   format = format.replace('dd', 'DD');
    //   return format;
    // }
  }
};
</script>

<style lang="scss" scoped>
.filter-value {
  display: flex;
}
.mr10 {
  margin-right: 10px;
}
.width-240 {
  width: 240px;
  &::v-deep {
    .el-input__inner {
      width: 240px;
    }
  }
}
.width-80 {
  width: 80px;
  &::v-deep {
    .el-input__inner {
      width: 80px;
    }
  }
}
.width-120 {
  width: 120px;
  &::v-deep {
    .el-input__inner {
      width: 120px;
    }
  }
}
.width-160 {
  width: 160px;
  &::v-deep {
    .el-input__inner {
      width: 160px;
    }
  }
}
</style>
